package com.example.image.impl

import android.content.Context
import android.graphics.drawable.Drawable
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestBuilder
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.example.image.IImageLoader
import com.example.image.ImageOptions
import java.io.File
import java.lang.ref.SoftReference

class GlideImpl : IImageLoader {
    override fun loadFromUrl(
        context: Context,
        path: String,
        imageView: ImageView,
        imageOptions: ImageOptions
    ) {
        realLoadImage(context,path,imageView,imageOptions)
    }

    override fun loadFromFile(
        context: Context,
        path: File,
        imageView: ImageView,
        imageOptions: ImageOptions
    ) {

    }

    override fun loadFromResoure(
        context: Context,
        path: Int,
        imageView: ImageView,
        imageOptions: ImageOptions
    ) {

    }

    fun realLoadImage(
        context: Context,
        path: Any,
        imageView: ImageView,
        imageOptions: ImageOptions
    ) {
        /**
         * 防止内存泄露
         */
        var softReference = SoftReference<Context>(context)

        /**
         * 获取Glide的build
         */
        var builder = Glide.with(softReference.get()!!).load(path)
        /**
         * 设置属性
         */
        setGlideOptions(builder,imageOptions)
        /**
         * 将图片设置到image
         */
        builder.into(imageView)
    }

    private fun setGlideOptions(builder: RequestBuilder<Drawable>, imageOptions: ImageOptions) {
        imageOptions?:return
        var glideOptions = RequestOptions()
        /**
         * 占位图
          */

        if (imageOptions.placeHolder!! >0){
            glideOptions?.placeholder(imageOptions.placeHolder!!)
        }
        /**
         * 错误图
         */
        if (imageOptions.errorholder!! >0){
            glideOptions?.placeholder(imageOptions.errorholder!!)
        }
        /**
         * 圆形
         */
        if (imageOptions.isCircle){
            glideOptions?.circleCrop()
        }
        /**
         * 内存
         */
        if (imageOptions.isMemoryCache){
            glideOptions?.skipMemoryCache(true)
        }
        /**
         *  磁盘
         */
        if (imageOptions.isDiskCache){
            glideOptions?.diskCacheStrategy(DiskCacheStrategy.NONE)
        }
        builder.apply(glideOptions)
    }
}